package com.superhelper.app.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.type.TypeReference;
import com.superhelper.app.common.CommonHelper;
import com.superhelper.app.common.Consts;
import com.superhelper.app.domain.Admin;
import com.superhelper.app.domain.DeliverRecordOrder;
import com.superhelper.app.domain.Order;
import com.superhelper.app.domain.OrderActivity;
import com.superhelper.app.domain.OrderGroup;
import com.superhelper.app.domain.OrderGroupItem;
import com.superhelper.app.domain.PageModel;
import com.superhelper.app.domain.Resp;
import com.superhelper.app.domain.RespOrder;
import com.superhelper.app.mapper.AdminMapper;
import com.superhelper.app.mapper.OrderMapper;
import com.superhelper.app.service.deliver.IDeliverService;
import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.PushMsgType;
import com.superhelper.common.domain.TakeOutOrderBackup;
import com.superhelper.common.domain.TakeOutOrderProcess;
import com.superhelper.common.domain.TakeOutOrderStatus;
import com.superhelper.common.domain.baidu.BdPushEntity;
import com.superhelper.common.service.AliMQProducerService;
import com.superhelper.common.service.BaiduService;
import com.superhelper.common.service.RedisService;
import com.superhelper.common.utils.JsonHelper;

@Service
public class OrderService {
    protected Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ElemeService elemeService;
    @Autowired
    private MtService mtService;
    @Autowired
    private DeliverService deliverService;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BaiduService baiduService;
    @Autowired
    private AliMQProducerService producerService;
    @Autowired
    private IDeliverService dadaService;

    public Resp getTakeOutOrder(Long userId, Long time, Integer pageSize, String target, String phone) {
        PageModel pageModel = new PageModel();
        if (StringUtils.isNotBlank(phone)) {
            if (phone.length() < 4) {
                pageModel.getQueryMap().put("daySn", phone);
            } else {
                pageModel.getQueryMap().put("phone", phone);
            }
        }
        List<String> listStatus = new ArrayList<String>();
        if (StringUtils.isBlank(target)) {
            target = "all";
        }
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        Date date_sub = CommonHelper.getDateFormat("yyyy-MM-dd", c.getTime());
        switch (target) {
        case "unprocessed":
            listStatus.add("'" + TakeOutOrderStatus.UNPROCESSED.getValue() + "'");
            break;
        case "valid":
            listStatus.add("'" + TakeOutOrderStatus.VALID.getValue() + "'");
            pageModel.getQueryMap().put("book", "0");
            break;
        case "delivering":
            listStatus.add("'" + TakeOutOrderStatus.DELIVERING.getValue() + "'");
            break;
        case "invalid":
            listStatus.add("'" + TakeOutOrderStatus.INVALID.getValue() + "'");
            break;
        case "settled":
            listStatus.add("'" + TakeOutOrderStatus.SETTLED.getValue() + "'");
            break;
        case "refunding":
            listStatus.add("'" + TakeOutOrderStatus.REFUNDING.getValue() + "'");
            listStatus.add("'" + TakeOutOrderStatus.APPLY_CANCEL.getValue() + "'");
            c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - 2);
            date_sub = CommonHelper.getDateFormat("yyyy-MM-dd", c.getTime());
            break;
        case "booking":
            listStatus.add("'" + TakeOutOrderStatus.VALID.getValue() + "'");
            pageModel.getQueryMap().put("book", "1");
            break;

        default:
            listStatus.add(target);
            break;
        }
        if (time == 0) {
            time = System.currentTimeMillis();
        }
        Date timeAt = new Date(time);
        pageModel.getQueryMap().put("status", StringUtils.join(listStatus, ","));
        List<AuserShop> shops = adminMapper.getAuserShopsByAuserId(userId);
        List<String> shopIds = new ArrayList<String>();
        shopIds.add("0");
        for (AuserShop s : shops) {
            shopIds.add(s.getShopId());
        }
        pageModel.getQueryMap().put("shopIds", StringUtils.join(shopIds, ","));
        int count = orderMapper.getTakeout_orderCount(pageModel, timeAt, date_sub);
        pageModel.setPageSize(pageSize);
        List<Order> list = orderMapper.getTakeout_order(pageModel, timeAt, date_sub);
        Map<Long, Order> map = new HashMap<Long, Order>();
        for (Order o : list) {
            map.put(o.getId(), o);
        }
        if (map.keySet().size() > 0) {
            List<Long> recordList = deliverService.getHasDeliverRecordByOrderIds(new ArrayList<Long>(map.keySet()));
            for (Long id : recordList) {
                if (map.containsKey(id)) {
                    map.get(id).setDeliver(true);
                } else {
                    map.get(id).setDeliver(false);
                }
            }
        }
        List<RespOrder> result = this.addGroupforOrder(list);
        return new Resp(Consts.Code.SUCCESS, null, result, count);
    }

    private List<RespOrder> addGroupforOrder(List<Order> list) {
        List<RespOrder> result = new ArrayList<RespOrder>();
        List<Long> orderIds = new ArrayList<Long>();
        for (Order order : list) {
            orderIds.add(order.getId());
        }
        if (orderIds.size() > 0) {
            List<OrderGroupItem> items = orderMapper.getTakeOutOrderGroupItem(StringUtils.join(orderIds, ","));
            Map<Long, List<OrderActivity>> activitysMap = this.getOrderActivitys(orderIds);
            for (Order order : list) {
                Map<String, OrderGroup> map = new HashMap<String, OrderGroup>();
                Map<String, List<OrderGroupItem>> basketGroupsMap = new HashMap<String, List<OrderGroupItem>>();
                for (OrderGroupItem item : items) {
                    if (order.getItems() == null) {
                        order.setItems(new ArrayList<OrderGroupItem>());
                    }
                    if (order.getOrderGroups() == null) {
                        order.setOrderGroups(new ArrayList<OrderGroup>());
                    }
                    if (order.getId().equals(item.getOrderId())) {

                        if (item.getType().equals("normal")) {// 统计商品份数
                            String temp = "";
                            if (StringUtils.isNoneBlank(item.getNewSpecs()) && !item.getNewSpecs().startsWith("{")
                                    && !item.getNewSpecs().startsWith("[")) {
                                if (!item.getName().contains(item.getNewSpecs())) {
                                    temp = item.getNewSpecs();

                                }
                            }
                            if (StringUtils.isNoneBlank(item.getAttributes()) && !item.getAttributes().startsWith("{")
                                    && !item.getAttributes().startsWith("[")) {
                                if (!item.getName().contains(item.getAttributes())) {
                                    temp = temp + "+" + item.getAttributes();
                                }
                            }
                            if (StringUtils.isNoneBlank(temp)) {
                                item.setName(item.getName() + "(" + temp + ")");
                            }
                            order.getItems().add(item);
                            order.setTotalQuantity(order.getTotalQuantity() + item.getQuantity());
                            if (!basketGroupsMap.containsKey(item.getGroupName())) {
                                basketGroupsMap.put(item.getGroupName(), new ArrayList<OrderGroupItem>());
                                basketGroupsMap.get(item.getGroupName()).add(item);
                            } else {
                                basketGroupsMap.get(item.getGroupName()).add(item);
                            }
                        } else if (item.getType().equals("extra")) {// 其他费用
                            if (map.containsKey(item.getName())) {
                                OrderGroup group = map.get(item.getName());
                                group.setQuantity(group.getQuantity() + item.getQuantity());
                                group.setPrice(BigDecimal.valueOf(group.getPrice())
                                        .add(BigDecimal.valueOf(item.getPrice())).doubleValue());
                            } else {
                                OrderGroup group = new OrderGroup();
                                group.setName(item.getName());
                                group.setQuantity(item.getQuantity());
                                group.setPrice(item.getPrice());
                                order.getOrderGroups().add(group);
                                map.put(item.getName(), group);
                            }
                        }
                    }

                }
                List<OrderActivity> activitys = activitysMap.get(order.getId());
                if (activitys != null) {
                    for (OrderActivity a : activitys) {
                        OrderGroup group = new OrderGroup();
                        group.setName(a.getName());
                        group.setQuantity(1);
                        group.setPrice(a.getAmount().doubleValue());
                        order.getOrderGroups().add(group);
                    }
                }

                List<Map<String, Object>> basketGroups = new ArrayList<Map<String, Object>>();
                for (String key : basketGroupsMap.keySet()) {
                    Map<String, Object> bmap = new HashMap<String, Object>();
                    bmap.put("name", key);
                    bmap.put("items", basketGroupsMap.get(key));
                    basketGroups.add(bmap);
                }
                order.setBasketGroups(basketGroups);
                RespOrder rOrder = new RespOrder();
                BeanUtils.copyProperties(order, rOrder);
                result.add(rOrder);
            }
        }
        return result;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private Map<Long, List<OrderActivity>> getOrderActivitys(List<Long> orderIds) {
        Map<Long, List<OrderActivity>> result = new HashMap<Long, List<OrderActivity>>();
        List<TakeOutOrderBackup> backups = orderMapper.getTakeout_order_backup(StringUtils.join(orderIds, ","));
        for (TakeOutOrderBackup b : backups) {
            try {
                Map<String, Object> map = JsonHelper.fromJson(b.getContent(), Map.class);
                String message = (String) map.get("message");
                String order = (String) map.get("order");
                if (StringUtils.isNotBlank(message)) {// 饿了么
                    map = JsonHelper.fromJson(message, Map.class);
                    List orderActivities = (List) map.get("orderActivities");
                    String json = JsonHelper.toJson(orderActivities);
                    List<OrderActivity> activitys = JsonHelper.fromJson(json, new TypeReference<List<OrderActivity>>() {
                    });
                    result.put(b.getOrderId(), activitys);
                } else if (StringUtils.isNotBlank(order)) {// 美团
                    map = JsonHelper.fromJson(order, Map.class);
                    String orderActivities = map.get("extras").toString();
                    List<Map> activitys = JsonHelper.fromJson(orderActivities, new TypeReference<List<Map>>() {
                    });
                    List<OrderActivity> list = new ArrayList<OrderActivity>();
                    for (Map m : activitys) {
                        OrderActivity a = new OrderActivity();
                        if (m.containsKey("reduce_fee")) {
                            a.setAmount(BigDecimal.valueOf(Double.parseDouble(m.get("reduce_fee") + "")));
                            a.setName(m.get("remark") + "");
                            list.add(a);
                        }
                    }
                    result.put(b.getOrderId(), list);
                } else {
                    result.put(b.getOrderId(), new ArrayList<OrderActivity>());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public List<RespOrder> querOrderToPrint(Long userId) {

        List<AuserShop> shops = adminMapper.getAuserShopsByAuserId(userId);
        List<String> shopIds = new ArrayList<String>();
        for (AuserShop s : shops) {
            shopIds.add(s.getShopId());
        }
        List<TakeOutOrderProcess> processList = orderMapper.querOrderToPrint(StringUtils.join(shopIds, ","));
        List<Long> orderids = new ArrayList<Long>();
        for (TakeOutOrderProcess p : processList) {
            orderids.add(p.getOrderId());
        }
        if (orderids.size() > 0) {
            List<Order> list = this.getOrderByIds(orderids);
            List<RespOrder> result = this.addGroupforOrder(list);
            for (RespOrder o : result) {
                for (TakeOutOrderProcess p : processList) {
                    if (o.getId().equals(p.getOrderId())) {
                        o.setPrintType(p.getType());// 打印类型
                        break;
                    }
                }
            }
            return result;
        }
        return Collections.emptyList();
    }

    public int updateProcess(String orderIds, Integer state) {
        int res = 0;
        if (StringUtils.isNoneBlank(orderIds) && orderIds.contains("-")) {
            String values[] = orderIds.split(",");
            for (String str : values) {
                String orderId = str.split("-")[0];
                String status = str.split("-")[1];
                if (status.equals(TakeOutOrderStatus.INVALID.getValue()) || status.equals("1")) {// status=0或者1时，是1.0.6版本之后的值
                    res = orderMapper.updateProcess(orderId, state, 0);
                    res = orderMapper.updateProcess(orderId, state, 1);
                } else {
                    res = orderMapper.updateProcess(orderId, state, 0);
                }
            }
        } else {// 兼容旧版
            res = orderMapper.updateProcess(orderIds, state, 0);
        }
        return res;
    }

    public RespOrder getOrderByOrderId(Long orderId) {
        Order order = orderMapper.getOrderByOrderId(orderId);
        List<Order> list = new ArrayList<Order>();
        list.add(order);
        List<RespOrder> result = this.addGroupforOrder(list);
        return result.get(0);
    }

    public List<Order> getOrderByIds(List<Long> ids) {
        List<Order> orders = orderMapper.getOrderByIds(StringUtils.join(ids, ","));
        // this.addGroupforOrder(orders);
        return orders;
    }

    @SuppressWarnings("unchecked")
    public Resp queryMsg(Long userId) {
        Admin user = adminMapper.getAdminById(userId);
        List<AuserShop> shops = adminMapper.getAuserShopsByAuserId(userId);
        String msg = null;
        for (AuserShop s : shops) {
            if (s.getOrderAuto() == 1) {
                String type = s.getShop_type();
                String shopId = s.getShopId();
                String key = String.format(com.superhelper.common.Consts.Redis.SUB_ORDER, type, shopId);
                msg = redisService.lpop(key);
                if (StringUtils.isNotBlank(msg)) {
                    break;
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(msg)) {
            log.info("mq-msg:{}", msg);
            map = JsonHelper.fromJson(msg, Map.class);
            Long orderId = Long.parseLong(map.get("orderId") + "");
            Order order = orderMapper.getOrderByOrderId(orderId);
            if (order != null) {
                if (order.getCreateAt().getTime() > user.getLoginAt().getTime()) {
                    log.info("mq-msg-right:{}", map.toString());
                    String type = (String) map.get("type");
                    Boolean book = (Boolean) map.get("book");
                    map.put("orderId", orderId);
                    map.put("type", type);
                    map.put("book", book);
                    if (PushMsgType.ORDER_APPLY_CANCEL.getValue().equals(map.get("type").toString())) {// 用户申请取消
                        map.put("type", PushMsgType.ORDER_CANCELED.getValue());
                    }
                }
            }
        }
        return new Resp(Consts.Code.SUCCESS, null, map);
    }

    public int updatePrintProcess(Long userId) {
        List<AuserShop> shops = adminMapper.getAuserShopsByAuserId(userId);
        List<String> shopIds = new ArrayList<String>();
        for (AuserShop s : shops) {
            shopIds.add(s.getShopId());
        }
        if (shopIds.size() > 0) {
            Date loginAt = new Date();
            return orderMapper.updateStatusByTime(StringUtils.join(shopIds, ","), loginAt);
        }
        return 0;
    }

    public boolean confirm(RespOrder order) throws Exception {
        boolean res = false;
        if (AuserShop.SHOP_ELEME.equals(order.getType())) {
            res = elemeService.confirmOrder(order.getShopId(), order.getPlfOrderId());
        } else if (AuserShop.SHOP_MEITUAN.equals(order.getType())) {
            res = mtService.confirmOrder(order.getShopId(), order.getPlfOrderId());
        } else if (AuserShop.SHOP_BAIDU.equals(order.getType())) {
            AuserShop shop = adminMapper.getAuserShopByType(order.getShopId(), AuserShop.SHOP_BAIDU);
            res = baiduService.confirmOrder(shop.getSource(), order.getPlfOrderId());
            // if (res) {
            // BdPushEntity entity = baiduService.statusPush(shop.getSource(),
            // order.getPlfOrderId(), "5", null, null);
            // producerService.sendBdOrder(entity);
            // }
        }
        return res;
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public boolean canelOrder(RespOrder order) throws Exception {
        int res = orderMapper.updateInvalid(order.getPlfOrderId(), order.getType());
        boolean f = false;
        if (res > 0) {
            // 达达发单也处理掉
            DeliverRecordOrder deliver = deliverService.getNeedCancelDeliverRecordByOrderId(order.getId());
            if (deliver != null) {
                deliverService.cancel(deliver.getId(), 4);// 顾客取消订单
            }
            if (AuserShop.SHOP_ELEME.equals(order.getType())) {
                f = elemeService.cancelOrder(order.getShopId(), order.getPlfOrderId());
            } else if (AuserShop.SHOP_MEITUAN.equals(order.getType())) {
                f = mtService.cancelOrder(order.getShopId(), order.getPlfOrderId());
            } else if (AuserShop.SHOP_BAIDU.equals(order.getType())) {
                AuserShop shop = adminMapper.getAuserShopByType(order.getShopId(), AuserShop.SHOP_BAIDU);
                f = baiduService.cancelOrder(shop.getSource(), order.getPlfOrderId());
                if (f) {
                    BdPushEntity entity = baiduService.statusPush(shop.getSource(), order.getPlfOrderId(), "10", "1",
                            "商户同意取消单");
                    producerService.sendBdOrder(entity);
                }
            }
            if (!f) {
                throw new Exception("canelOrder error");
            }
        }
        return f;
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public boolean disagreeRefund(RespOrder order) throws Exception {
        int res = orderMapper.updateDisInvalid(order.getPlfOrderId(), order.getType());
        boolean f = false;
        if (res > 0) {
            if (AuserShop.SHOP_ELEME.equals(order.getType())) {
                f = elemeService.disagreeRefund(order.getShopId(), order.getPlfOrderId());
            } else if (AuserShop.SHOP_MEITUAN.equals(order.getType())) {
                f = mtService.disagreeRefund(order.getShopId(), order.getPlfOrderId());
            } else if (AuserShop.SHOP_BAIDU.equals(order.getType())) {
                f = true;
            }
            if (!f) {
                throw new Exception("disagreeRefund error");
            }
        }
        return f;
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public boolean agreeRefund(RespOrder order) throws Exception {
        int res = orderMapper.updateInvalid(order.getPlfOrderId(), order.getType());
        boolean f = false;
        if (res > 0) {
            // 达达发单也处理掉
            DeliverRecordOrder deliver = deliverService.getNeedCancelDeliverRecordByOrderId(order.getId());
            if (deliver != null) {
                deliverService.cancel(deliver.getId(), 4);// 顾客取消订单
            }
            if (AuserShop.SHOP_ELEME.equals(order.getType())) {
                f = elemeService.agreeRefund(order.getShopId(), order.getPlfOrderId());
            } else if (AuserShop.SHOP_MEITUAN.equals(order.getType())) {
                f = mtService.agreeRefund(order.getShopId(), order.getPlfOrderId());
            } else if (AuserShop.SHOP_BAIDU.equals(order.getType())) {
                AuserShop shop = adminMapper.getAuserShopByType(order.getShopId(), AuserShop.SHOP_BAIDU);
                f = baiduService.refundOrder(shop.getSource(), order.getPlfOrderId());

                if (f) {
                    BdPushEntity entity = baiduService.statusPush(shop.getSource(), order.getPlfOrderId(), "10", "1",
                            "商户同意退款");
                    producerService.sendBdOrder(entity);
                }
            }
            if (!f) {
                throw new Exception("agreeOrder error");
            }
        }
        return f;
    }

    public List<RespOrder> queryNeedDeal(Long userId) {

        List<AuserShop> shops = adminMapper.getAuserShopsByAuserId(userId);
        List<String> shopIds = new ArrayList<String>();
        for (AuserShop s : shops) {
            shopIds.add(s.getShopId());
        }
        if (shopIds.size() > 0) {
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            Date date_sub = CommonHelper.getDateFormat("yyyy-MM-dd", c.getTime());
            List<String> listStatus = new ArrayList<String>();
            listStatus.add("'" + TakeOutOrderStatus.UNPROCESSED.getValue() + "'");
            listStatus.add("'" + TakeOutOrderStatus.REFUNDING.getValue() + "'");
            listStatus.add("'" + TakeOutOrderStatus.APPLY_CANCEL.getValue() + "'");
            long time = System.currentTimeMillis();
            Date timeAt = new Date(time);
            PageModel pageModel = new PageModel();
            pageModel.getQueryMap().put("shopIds", StringUtils.join(shopIds, ","));
            pageModel.getQueryMap().put("status", StringUtils.join(listStatus, ","));

            List<String> refundStatusList = new ArrayList<String>();
            refundStatusList.add("'noRefund'");
            refundStatusList.add("'applied'");
            pageModel.getQueryMap().put("refundStatus", StringUtils.join(refundStatusList, ","));

            pageModel.setPageSize(10);
            List<Order> list = orderMapper.getTakeout_order(pageModel, timeAt, date_sub);
            List<Order> tmpList = new ArrayList<Order>();
            for (Order o : list) {
                boolean flag = redisService.sIsMembers(com.superhelper.app.common.Consts.Cache.SMS_REFUNDING_KEY,
                        String.valueOf(o.getId()));
                if (!flag) {
                    redisService.saddSet(com.superhelper.app.common.Consts.Cache.SMS_REFUNDING_KEY,
                            String.valueOf(o.getId()));
                    tmpList.add(o);
                }
            }
            List<RespOrder> result = this.addGroupforOrder(tmpList);
            return result;
        }
        return Collections.emptyList();
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public int updateDeliverTime(Long orderId, String time) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date deliverTime = sdf.parse(time);
        int res = orderMapper.updateTakeOrderDeliverTime(orderId, deliverTime);
        if (res > 0) {
            DeliverRecordOrder record = deliverService.getNeedCancelDeliverRecordByOrderId(orderId);
            if (record != null) {
                if (record.getStatus() == 3) {// 配送中，不允许修改
                    log.info("updateDeliverTime delivering-{}", orderId);
                    return -1;
                }
                int ress = deliverService.cancel(record.getId(), 10000);
                if (ress > 0) {
                    dadaService.addBookTask(orderId);
                }
            }
        }
        return res;
    }

    public String getContentToPrint(RespOrder order) {
        // RespOrder order = this.getOrderByOrderId(orderId);
        StringBuffer contents = new StringBuffer();
        contents.append("******订单起始********<BR>");
        if (order.getType().equals(AuserShop.SHOP_ELEME)) {
            contents.append("<CB>饿了么#" + order.getDaySn() + "</CB><BR>");
        } else if (order.getType().equals(AuserShop.SHOP_MEITUAN)) {
            contents.append("<CB>美团外卖#" + order.getDaySn() + "</CB><BR>");
        } else if (order.getType().equals(AuserShop.SHOP_BAIDU)) {
            contents.append("<CB>百度外卖#" + order.getDaySn() + "</CB><BR>");
        }
        if (order.getBook()) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            String time = sdf.format(order.getDeliverTime());
            contents.append("<C><W>预约" + time + "送达</W></C><BR>");
        } else {
            contents.append("<C><W>立即送达</W></C><BR>");
        }
        contents.append("<L>" + order.getShopName() + "</L><BR>");
        contents.append("单号:" + order.getPlfOrderId() + "<BR>");
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
        String createAt = sdf.format(order.getCreateAt());
        contents.append("下单时间:" + createAt + "<BR>");
        contents.append("<B>备注:" + order.getDescription() + "</B><BR>");
        contents.append("<C>-----------菜品------------</C><BR>");

        for (OrderGroupItem item : order.getItems()) {
            contents.append("<L>" + item.getName() + "</L><BR>");
            contents.append("<RIGHT><L>x" + item.getQuantity() + "  " + item.getPrice() * item.getQuantity()
                    + "</L></RIGHT><BR>");
        }
        contents.append("<C>-----------其他------------</C><BR>");
        for (OrderGroup item : order.getOrderGroups()) {
            contents.append("<L>" + item.getName() + ":" + item.getPrice() + "</L><BR>");
        }
        contents.append("<L>配送费：" + order.getDeliverFee() + "</L><BR>");
        contents.append("<C>------------------------</C><BR>");
        contents.append("<B>已付:" + order.getTotalPrice() + "</B><BR>");
        contents.append("<BR>");
        contents.append("<B>地址:" + order.getDeliverPoi() + "</B><BR>");
        contents.append("<BR>");
        contents.append("<B>姓名:" + order.getConsigness() + "</B><BR>");
        contents.append("<B>" + order.getPhone() + "</B><BR>");
        contents.append("<C>******订单结束*******</C><BR>");
        contents.append("<BR>");
        contents.append("<BR>");
        contents.append("<BR>");
        return contents.toString();
    }

    public int updateWifiProcess(Long orderId, String wifi_orderId, int state) {
        return orderMapper.updateWifiProcess(orderId, wifi_orderId, state);
    }

}
